from utils.mysql import *
from config.contest import *
from utils.writer import ExcelDataDriver
from utils.utils import *
import pytest,allure

# 链接数据库
@pytest.fixture(scope="module")
def sql():
    sql = A3mall_db(
        host='10.59.9.12',
        user='root',
        pwd='yidong666',
        database='a3mall'
    )
    yield sql
    sql.close()

@pytest.fixture(scope='module')
def api():
    api = lianjie(base_url='http://10.59.9.12:7001')
    log()
    yield api

@pytest.fixture(scope='module')
def A3mall_login_token(api):
    data = {
        'username': '15235688537',
        'password': '123456'
    }
    response = api.post('/api/public/login',data=data)
    token = response.json()['data']['token']
    return {'token':token}

# @pytest.mark.parametrize('yaml',read_yaml())
def test_A3mall_login(sql,api):
    data = {
        # 'username':yaml['username'],
        # 'password':yaml['password']
        'username': '15235688537',
        'password': '123456'
    }
    response = api.post('/api/public/login',data=data)
    # token = response.json()['data']['token']
    # print(token)
    # assert response.json()['info'] == yaml['exp']
    # 数据库断言
    try:
        # '{data['username']}'
        dy1 = sql.select("select username from mall_users where username = '15235688537'")
        assert dy1[0][0] == data['username'], '用户名与数据库不匹配'
        dy2 = sql.select("select amount from mall_users where username = '15235688537'")
        print(dy2[0][0])
        assert dy2[0][0] == data['amount'], '金额与数据库不匹配'
    except Exception as q:
        print(q)
    # 状态码
    assert response.status_code == 200
    # 响应文本
    assert "ok" in response.text
    # 断言响应时间 ≤ 2秒（2000毫秒）
    assert response.elapsed.total_seconds() <= 2, "响应时间超时"
    print('---------------***-----------------')
    ExcelDataDriver.write_excel(
        r'E:\gg4\Auto_wms\Api_A3mall\data\inbound.xlsx',
        'Sheet1',2, f'{response.json()['data']['token']}'
    )

def test_02(api,A3mall_login_token):
    token = A3mall_login_token['token']
    # 商品 http://10.59.9.12:7001/api/goods/view?id=1
    response = api.get('/api/goods/view?id=1')
    print(response.json())
    print('---------------***-----------------')
    # 业务逻辑断言1，断言是否成功获取token
    assert token , '获取token失败'
    # 依赖
    id = response.json()['data']['goods']['id']
    # 创建订单 http://10.59.9.12:7001/api/order/confirm?id=1&type=buy&sku_id=&num=1&shipping_type=1
    headers = {
        "auth-token":"Bearer "+token
    }
    """业务逻辑断言2，断言是否获取到商品id"""
    assert id ,'未获取到ID'
    response = api.get(f'/api/order/confirm?id={id}&type=buy&sku_id=&num=1&shipping_type=1',headers=headers)
    print(response.json())
    print('---------------***-----------------')
    # 提交订单 http://10.59.9.12:7001/api/order/create
    # {"id":"1","type":"buy","address_id":39,"store_id":1,"shipping_type":1,"bonus_id":"0","payment":"balance","remarks":"","source":1,"url":"http://10.59.9.12:7001/wap/pages/cart/confirm?id=1&sku_id=&num=1&type=buy","sku_id":"","num":"1"}
    tdata = {
        "id": id,
        "type": "buy",
        "address_id": 39,
        "store_id": 1,
        "shipping_type": 1,
        "bonus_id": "0",
        "payment": "balance",
        "remarks": "", "source": 1,
        "url": "http://10.59.9.12:7001/wap/pages/cart/confirm?id=1&sku_id=&num=1&type=buy",
        "sku_id": "",
        "num": "1"
    }
    tresponse = api.post('/api/order/create',headers = headers,data = tdata)
    print(tresponse.json())
    print('---------------***-----------------')

    allure.attach(str(response.json()), "登录响应体", allure.attachment_type.JSON)

    # 2. Allure响应时间断言
    with allure.step("断言：登录接口响应时间≤2秒"):
        actual_time = response.elapsed.total_seconds()
        allure.attach(f"实际耗时：{actual_time:.2f}秒", "耗时详情")
        assert actual_time < 2, f"超时（{actual_time:.2f}秒）"

def test_read():
    data = ExcelDataDriver.read_excel(r'E:\gg4\Auto_wms\Api_A3mall\data\inbound.xlsx', 'Sheet1')
    for item in data:
        print('---------------***读取-----------------')
        print(item)

if __name__ == '__main__':
    pytest.main(['-s'])
